#!/bin/bash
#
#

functionname=`basename "$0"`

#####################################################################

function PrintHelp()
{
  echo "Make a mask that covers the CT-cone for a specific image."
  echo
  echo "Usage:"
	echo $functionname
	echo "  -in      input filename"
	echo "  [-out]   outputFilename, default in + _ConeMask.mhd"
	echo "  [-e]     erosion value, default 0"
	echo
	echo "Note: 3D images are expected."
}

#####################################################################

if [[ $# = 0 || $1 == "--help" ]]
then
  PrintHelp
  exit 64
fi

erode=0
argv=($*)
for (( i = 0; i < $#; ++i ))
do
	arg=${argv[$i]}
	if [[ $arg == "-in" ]]
	then
		let i=$i+1
		in=${argv[$i]}
	fi
	if [[ $arg == "-out" ]]
	then
		let i=$i+1
		out=${argv[$i]}
	fi
	if [[ $arg == "-e" ]]
	then
		let i=$i+1
		erode=${argv[$i]}
	fi
done

if [[ $in == "" ]]
then
	echo "ERROR: you must specify -in"
	exit 1
fi

if [[ ! -e $in ]]
then
	echo "ERROR: The file $in does not exist"
	exit 1
fi

if [[ $out == "" ]]
then
	base=${in%.*}
	ext=${in##*.}
	out=$base"_ConeMask."$ext
fi

#####################################################################

dimx=`pxgetimageinformation -in $in -sz -i 0`
dimy=`pxgetimageinformation -in $in -sz -i 1`
dimz=`pxgetimageinformation -in $in -sz -i 2`
spx=`pxgetimageinformation -in $in -sp -i 0`

centerx=`echo $dimx/2-1 | bc`
centery=`echo $dimy/2-1 | bc`
centerz=`echo $dimz/2-1 | bc`
radius=`echo "($dimx/2-1-$erode)*$spx" | bc`

pxcreatecylinder -in $in -out $out -c $centerx $centery $centerz -r $radius
pxcompressimage $out >> /dev/null

# Return success
exit 0

